<template>

  <el-dialog title="员工导入" width="30%" :visible="visible" @close="$emit('update:visible',false)">
    <input ref="file" type="file" accept=".xlsx, .xls" @change="handleChange">
    <div class="area" @drop="handleDrop" @dragover="handleDragover" @dragenter="handleDragover">
      <i class="el-icon-upload" style="font-size:50px;color:#ccc" />
      <p style="color:#409eff" class="hovver" @click="downfile">下载导入文件</p>
      <p>将文件拖到此处或
        <a style="color:#409eff" href="javascript:;" @click="$refs.file.click()">点击上传</a>
      </p>
    </div>
  </el-dialog>

</template>

<script>
import { downfile, importExcel } from '@/api/employee'
import { saveAs } from 'file-saver'
export default {
  props: {
    visible: {
      type: Boolean,
      required: true
    }
  },
  data() {
    return {}
  },
  methods: {
    async downfile() {
      const res = await downfile()
      console.log(res)
      saveAs(res, '员工导入模板.xlsx')
    },
    async handleChange(e) {
      console.log(e)
      const files = e.target.files
      if (files.length === 0) {
        return this.$message.error('请选择要上传的文件')
      }
      console.log(files[0])
      await this.upload(files[0])
    },
    async upload(file) {
      this.$refs.file.value = null // 防止用户提交两次 文件名字重复 change第二次就不会触发
      const fd = new FormData()
      fd.append('file', file)
      const res = await importExcel(fd)
      console.log(res)
      this.$message.success('上传成功')
      this.$emit('update:visible', false)
      this.$emit('getemployee')
    },
    async  handleDrop(e) {
      e.stopPropagation()
      e.preventDefault()
      console.log(e)
      const files = e.dataTransfer.files
      if (files.length === 0) {
        return this.$message.error('请选择要上传的文件')
      }
      console.log(files[0])
      await this.upload(files[0])
    },
    handleDragover(e) {
      e.stopPropagation()
      e.preventDefault()
      e.dataTransfer.dropEffect = 'move'
    }
  }
}
</script>

<style scoped lang='scss'>
.area {
    width: 300px;
    height: 140px;
    border: 1px dashed #ccc;
    text-align: center;
    margin: 0 auto;
    // line-height: 140px;
}
 ::v-deep input[type="file"] {
    display: none;
}
.hovver {
    cursor: pointer;
}
</style>
